package com.softer.wxzj.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 参数处理与校验
 */
public class ParamUtils {
    private static final Logger LOGGER= LoggerFactory.getLogger(ParamUtils.class);
    private static final String STANDARD_URL_REG = "^(http)\\://(((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])|([a-zA-Z0-9_\\-\\.])+\\.(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|uk|me))((:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&amp;%\\$#\\=~])*)$";
    private static final String STANDARD_EMAIL_REG="^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    private static final String USERNAMEREG= "[\u4e00-\u9fa5\uF900-\uFA2D\\w]+";
   public enum RegType{
       EMAIL ,URL ,USERNAME
   }
    /**
     * 所有的对象都不空Null
     * etc：
     * arg:    空       ----空数组：false
     * arg:  null   --->(Object[])null   : false
     * arg:(Object)null--->Object[null]:false;
     * arg:(Object[])null----->(Object[])null :false;
     * ……
     * @param arg  参数
     * @return
     */
    public static boolean allNotNull(Object ...arg){
        if(arg==null||arg.length==0) {
            return false;
        }
        for (int i = 0; i < arg.length; i++) {
            Object o = arg[i];
            if(o==null) {
                return false;
            }
            if(o instanceof Object[]){
                if(((Object[])o).length==0) {
                    return false;
                }
            }
            if(o instanceof String){
                String o1 = (String) o;
                if (StringUtils.isBlank(o1)) {
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 不是所有的对象都是Null
     * @param arg  待检测的对象
     * @return
     */
    public static boolean notAllNull(Object ...arg){
        if(arg==null||arg.length==0) {
            return false;
        }
        for (int i = 0; i < arg.length; i++) {
            Object o = arg[i];
            if(o==null) {
                continue;
            }
            if(o instanceof String){
                String o1 = (String) o;
                if(StringUtils.isNotBlank(o1)) {
                    return true;
                }
                continue;
            }
            return true;
        }
        return false;
    }

    /**
     * 通用正则验证
     * @param items   验证数据
     * @param regtype 验证类型
     * @return true全部通过，false有非法
     */
    public static boolean commonRegCheck(RegType regtype,String... items) {
        if(items==null||items.length==0) {
            return false;
        }
        String reg;
        switch (regtype){
            case URL:
                reg=STANDARD_URL_REG;
                break;
            case EMAIL:
                reg=STANDARD_EMAIL_REG;
                break;
            case USERNAME:
                reg=USERNAMEREG;
                break;
            default:
                return false;
        }
        return doCheck(items,reg);
    }

    private static boolean doCheck(String[] urls,String regType) {
        for (int i = 0; i < urls.length; i++) {
            if (StringUtils.isBlank(urls[i])) {
                continue;
            }
            Pattern pattern = Pattern.compile(regType);
            Matcher matcher = pattern.matcher(urls[i]);
            if (!matcher.matches()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 非空参数验证
     *
     * @param params 参数
     */
    public static boolean verifyRequestParam(Object... params) {
        for (Object param : params) {
            if (param instanceof String && StringUtils.isBlank(String.valueOf(param))) {
                return false;
            }
            if (param == null) {
                return false;
            }
        }
        return true;
    }

    public static void notEmpty(Object obj, String message) {
        if(obj == null) {
            throw new IllegalArgumentException(message + " must be specified");
        } else if(obj instanceof String && obj.toString().trim().length() == 0) {
            throw new IllegalArgumentException(message + " must be specified");
        } else if(obj.getClass().isArray() && Array.getLength(obj) == 0) {
            throw new IllegalArgumentException(message + " must be specified");
        } else if(obj instanceof Collection && ((Collection)obj).isEmpty()) {
            throw new IllegalArgumentException(message + " must be specified");
        } else if(obj instanceof Map && ((Map)obj).isEmpty()) {
            throw new IllegalArgumentException(message + " must be specified");
        }
    }
    public static String decodeString(String param,String  decodeType){
        try {
            return URLDecoder.decode(param, decodeType);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("以[{}]解码[{}]出现异常[{}]",param,decodeType, ErrorToLogUtils.getTrace(e));
            return param;
        }
    }
    public static String encodeString(String param,String  encodeType){
        try {
            return URLEncoder.encode(param, encodeType);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("以[{}]编码[{}]出现异常[{}]",param,encodeType, ErrorToLogUtils.getTrace(e));
            return param;
        }
    }
}
